<template>
  <div class="app-container">
    <!-- 功能概述卡片 -->
    <el-card class="overview-card">
      <template #header>
        <div class="card-header">
          <span>功能概述</span>
        </div>
      </template>
      <div v-loading="overviewLoading">
        <div class="overview-content" v-if="overviewData">
          {{ overviewData }}
        </div>
        <el-empty v-else description="暂无功能概述信息" />
      </div>
    </el-card>

    <!-- 监测量列表卡片 -->
    <el-card class="monitoring-list-card mt-2">
      <template #header>
        <div class="card-header">
          <span>监测量列表</span>
          <div>
            <el-input v-model="monitoringSearch" placeholder="搜索监测量" clearable prefix-icon="Search"
              style="width: 200px; margin-right: 10px" @input="handleMonitoringSearch" />
            <el-button type="primary" @click="handleAddCommonMonitoring" :disabled="!selectedMonitoring.length">设为常用</el-button>
          </div>
        </div>
      </template>

      <div class="table-container">
        <el-table 
          ref="monitoringTableRef" 
          :data="filteredMonitoringList" 
          border 
          v-loading="monitoringLoading"
          @selection-change="handleMonitoringSelectionChange"
          style="width: 100%"
          height="400px"
        >
          <el-table-column type="selection" width="55" align="center" fixed="left" />
          <el-table-column type="index" label="序号" width="60" align="center" fixed="left" />
          <el-table-column prop="monitorName" label="监测量名称" align="center" min-width="120" />
          <el-table-column prop="monitorCode" label="监测量编码" align="center" min-width="120" />
          <el-table-column prop="monitorUnit" label="单位" align="center" min-width="80" />
          <el-table-column prop="monitorType" label="监测量类型" align="center" min-width="120" />
          <el-table-column label="状态" align="center" width="80" fixed="right">
            <template #default="{ row }">
              <el-tag :type="row.status === 0 ? 'success' : 'danger'">
                {{ row.status === 0 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="预警状态" align="center" width="100" fixed="right">
            <template #default="{ row }">
              <el-tag :type="row.warningStatus === 0 ? 'success' : 'warning'">
                {{ row.warningStatus === 0 ? '开启' : '关闭' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 常用监测量配置 -->
    <el-card class="common-config-card mt-2">
      <template #header>
        <div class="card-header">
          <span>常用监测量配置</span>
          <!-- <el-button type="primary" @click="handleAddCommonConfig">新增配置</el-button> -->
        </div>
      </template>

      <div class="table-container">
        <el-table 
          :data="commonMonitoringList" 
          border 
          v-loading="commonLoading" 
          style="width: 100%"
          height="300px"
        >
          <el-table-column type="index" label="序号" width="60" align="center" fixed="left" />
          <el-table-column prop="aliasName" label="显示名称" align="center" min-width="150">
            <template #default="{ row }">
              {{ row.aliasName || row.metricCode }}
            </template>
          </el-table-column>
          <el-table-column prop="aliasUnit" label="显示单位" align="center" min-width="100">
            <template #default="{ row }">
              {{ row.aliasUnit || '默认单位' }}
            </template>
          </el-table-column>
          <el-table-column label="是否常用" align="center" width="100">
            <template #default="{ row }">
              <el-switch v-model="row.isCommon" :active-value="1" :inactive-value="0"
                @change="handleCommonStatusChange($event,row)" />
            </template>
          </el-table-column>
          <!-- <el-table-column label="启用状态" align="center" width="100">
            <template #default="{ row }">
              <el-switch v-model="row.enabled" :active-value="1" :inactive-value="0"
                @change="handleEnabledStatusChange(row)" />
            </template>
          </el-table-column> -->
          <el-table-column label="操作" width="200" align="center" fixed="right">
            <template #default="{ row }">
              <!-- <el-button size="small" type="primary" @click="handleEditCommonConfig(row)">编辑</el-button> -->
              <el-button size="small" type="danger" @click="handleDeleteCommonConfig(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 常用筛选配置 -->
    <el-card class="filter-config-card mt-2">
      <template #header>
        <div class="card-header">
          <span>常用筛选配置</span>
          <el-button type="primary" @click="handleAddFilterConfig">新增筛选</el-button>
        </div>
      </template>

      <div class="table-container">
        <el-table 
          :data="commonFilterList" 
          border 
          v-loading="filterLoading" 
          style="width: 100%"
          height="300px"
        >
          <el-table-column type="index" label="序号" width="60" align="center" fixed="left" />
          <el-table-column prop="optionCode" label="筛选编码" align="center" min-width="120" />
          <el-table-column prop="optionName" label="筛选名称" align="center" min-width="150" />
          <el-table-column prop="metricNames" label="关联监测量" align="center" min-width="200" />
          <el-table-column label="启用状态" align="center" width="100">
            <template #default="{ row }">
              <el-switch v-model="row.isEnabled" :active-value="1" :inactive-value="0"
                @change="handleFilterStatusChange($event,row)" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center" fixed="right">
            <template #default="{ row }">
              <!-- <el-button size="small" type="primary" @click="handleEditFilterConfig(row)">编辑</el-button> -->
              <el-button size="small" type="danger" @click="handleDeleteFilterConfig(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 常用监测量配置对话框 -->
    <el-dialog v-model="commonConfigDialog.visible" :title="commonConfigDialog.title" width="600px">
      <el-form ref="commonConfigFormRef" :model="commonConfigForm" :rules="commonConfigRules" label-width="100px">
        <el-form-item label="监测量" prop="metricId">
          <el-select v-model="commonConfigForm.metricId" placeholder="请选择监测量" filterable style="width: 100%"
            @change="handleMetricChange">
            <el-option v-for="item in monitoringList" :key="item.monitorId"
              :label="`${item.monitorName} (${item.monitorCode})`" :value="item.monitorId" />
          </el-select>
        </el-form-item>
        <el-form-item label="显示名称">
          <el-input v-model="commonConfigForm.aliasName" placeholder="为空则使用监测量名称" />
        </el-form-item>
        <el-form-item label="显示单位">
          <el-input v-model="commonConfigForm.aliasUnit" placeholder="为空则使用监测量单位" />
        </el-form-item>
        <el-form-item label="排序号">
          <el-input-number v-model="commonConfigForm.orderNo" :min="0" controls-position="right" />
        </el-form-item>
        <el-form-item label="是否常用">
          <el-radio-group v-model="commonConfigForm.isCommon">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="启用状态">
          <el-radio-group v-model="commonConfigForm.enabled">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="commonConfigForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="commonConfigDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveCommonConfig">保存</el-button>
      </template>
    </el-dialog>

    <!-- 常用筛选配置对话框 -->
    <el-dialog v-model="filterConfigDialog.visible" :title="filterConfigDialog.title" width="700px">
      <el-form ref="filterConfigFormRef" :model="filterConfigForm" :rules="filterConfigRules" label-width="120px">
        <el-form-item label="筛选编码" prop="optionCode">
          <el-input v-model="filterConfigForm.optionCode" placeholder="请输入筛选编码（如 F001）" />
        </el-form-item>
        <el-form-item label="筛选名称" prop="optionName">
          <el-input v-model="filterConfigForm.optionName" placeholder="请输入筛选名称（如 环境监测）" />
        </el-form-item>
        <el-form-item label="关联监测量" prop="metricIds">
          <el-select v-model="filterConfigForm.metricIds" multiple placeholder="请选择关联的监测量" style="width: 100%">
            <!-- <el-option v-for="item in monitoringList" :key="item.monitorId"
              :label="`${item.monitorName} (${item.monitorCode})`" :value="item.monitorId" /> -->
              <el-option v-for="item in commonMonitoringList" :key="item.metricId"
              :label="item.aliasName" :value="item.metricId" />
          </el-select>
        </el-form-item>
        <el-form-item label="启用状态">
          <el-radio-group v-model="filterConfigForm.isEnabled">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="filterConfigDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveFilterConfig">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// API接口
import {
  getFunctionOverview,
  getMonitoringList,
  getCommonMonitoringList,
  addCommonMonitoring,
  deleteCommonMonitoring,
  getCommonFilterList,
  addCommonFilter,
  deleteCommonFilter,
  setCommonMonitoring,
  setCommonFilter
} from '@/api/dispatch/affair/monitoredQuantity'

// 响应式数据
const overviewLoading = ref(false)
const monitoringLoading = ref(false)
const commonLoading = ref(false)
const filterLoading = ref(false)

// 数据存储
const overviewData = ref('')
const monitoringList = ref([])
const commonMonitoringList = ref([])
const commonFilterList = ref([])
const selectedMonitoring = ref([])

// 搜索参数
const monitoringSearch = ref('')

// 对话框控制
const commonConfigDialog = reactive({
  visible: false,
  title: '新增常用监测量配置'
})

const filterConfigDialog = reactive({
  visible: false,
  title: '新增常用筛选配置'
})

// 表单数据
const commonConfigForm = reactive({
  id: null,
  metricId: '',
  metricCode: '',
  aliasName: '',
  aliasUnit: '',
  orderNo: 0,
  isCommon: 1,
  enabled: 1,
  remark: ''
})

const filterConfigForm = reactive({
  id: null,
  optionCode: '',
  optionName: '',
  metricIds: [],
  isEnabled: 1
})

// 表单验证规则
const commonConfigRules = reactive({
  metricId: [
    { required: true, message: '请选择监测量', trigger: 'change' }
  ]
})

const filterConfigRules = reactive({
  optionCode: [
    { required: true, message: '请输入筛选编码', trigger: 'blur' }
  ],
  optionName: [
    { required: true, message: '请输入筛选名称', trigger: 'blur' }
  ],
  metricIds: [
    { required: true, message: '请选择关联监测量', trigger: 'change' }
  ]
})

// 计算属性
const filteredMonitoringList = computed(() => {
  if (!monitoringSearch.value) return monitoringList.value
  const search = monitoringSearch.value.toLowerCase()
  return monitoringList.value.filter(item =>
    item.monitorName.toLowerCase().includes(search) ||
    item.monitorCode.toLowerCase().includes(search) ||
    item.monitorType.toLowerCase().includes(search)
  )
})

// 初始化加载数据
onMounted(() => {
  loadAllData()
})

// 加载所有数据
const loadAllData = async () => {
  try {
    await Promise.all([
      loadFunctionOverview(),
      loadMonitoringList(),
      loadCommonMonitoringList(),
      loadCommonFilterList()
    ])
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  }
}

// 刷新所有数据
const refreshAllData = async () => {
  try {
    ElMessage.info('正在刷新数据...')
    await loadAllData()
    ElMessage.success('数据刷新成功')
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('刷新数据失败')
  }
}

// 加载功能概述
const loadFunctionOverview = async () => {
  try {
    overviewLoading.value = true
    const res = await getFunctionOverview()
    overviewData.value = res.data || '暂无功能概述信息'
  } catch (error) {
    console.error('加载功能概述失败:', error)
    throw error
  } finally {
    overviewLoading.value = false
  }
}

// 加载监测量列表
const loadMonitoringList = async () => {
  try {
    monitoringLoading.value = true
    const res = await getMonitoringList()
    monitoringList.value = res.data || []
    // 清除选择
    selectedMonitoring.value = []
  } catch (error) {
    console.error('加载监测量列表失败:', error)
    throw error
  } finally {
    monitoringLoading.value = false
  }
}

// 加载常用监测量配置
const loadCommonMonitoringList = async () => {
  try {
    commonLoading.value = true
    const res = await getCommonMonitoringList()
    commonMonitoringList.value = res.data || []
  } catch (error) {
    console.error('加载常用监测量配置失败:', error)
    throw error
  } finally {
    commonLoading.value = false
  }
}

// 加载常用筛选配置
const loadCommonFilterList = async () => {
  try {
    filterLoading.value = true
    const res = await getCommonFilterList()
    commonFilterList.value = res.data || []
  } catch (error) {
    console.error('加载常用筛选配置失败:', error)
    throw error
  } finally {
    filterLoading.value = false
  }
}

// 监测量搜索
const handleMonitoringSearch = () => {
  // 搜索功能已通过计算属性实现
}

// 监测量选择变化
const handleMonitoringSelectionChange = (selection) => {
  selectedMonitoring.value = selection
}

// 设为常用监测量
const handleAddCommonMonitoring = async () => {
  if (selectedMonitoring.value.length === 0) {
    ElMessage.warning('请选择要设为常用的监测量')
    return
  }

  try {
    const metricIds = selectedMonitoring.value.map(item => item.monitorId)
    await addCommonMonitoring({ metricIds })
    ElMessage.success('设置成功')
    // 设置成功后刷新所有数据
    await refreshAllData()
  } catch (error) {
    console.error('设置常用监测量失败:', error)
    ElMessage.error('设置常用监测量失败')
  }
}

// 新增常用监测量配置
const handleAddCommonConfig = () => {
  commonConfigDialog.title = '新增常用监测量配置'
  commonConfigDialog.visible = true
  resetCommonConfigForm()
}

// 编辑常用监测量配置
const handleEditCommonConfig = (row) => {
  commonConfigDialog.title = '编辑常用监测量配置'
  commonConfigDialog.visible = true
  Object.assign(commonConfigForm, row)
}

// 删除常用监测量配置
const handleDeleteCommonConfig = async (row) => {
  try {
    await ElMessageBox.confirm(`确定删除常用监测量配置 "${row.aliasName || row.metricCode}" 吗？`, '提示', {
      type: 'warning'
    })

    await deleteCommonMonitoring(row.id)
    ElMessage.success('删除成功')
    // 删除成功后刷新所有数据
    await refreshAllData()
  } catch {
    // 用户取消删除
  }
}

// 常用状态变化
const handleCommonStatusChange = async (value,row) => {
  try {
    // 这里应该调用更新接口，但接口文档中没有提供更新接口
    ElMessage.success('状态更新成功')
    
    await setCommonMonitoring({
      id: row.id,
      isCommon: value
    });
    // 刷新数据
    await loadCommonMonitoringList()
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('更新状态失败')
  }
}

// 启用状态变化
const handleEnabledStatusChange = async (row) => {
  try {
    // 这里应该调用更新接口，但接口文档中没有提供更新接口
    ElMessage.success('状态更新成功')
    // 刷新数据
    await loadCommonMonitoringList()
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('更新状态失败')
  }
}

// 新增常用筛选配置
const handleAddFilterConfig = () => {
  filterConfigDialog.title = '新增常用筛选配置'
  filterConfigDialog.visible = true
  resetFilterConfigForm()
}

// 编辑常用筛选配置
const handleEditFilterConfig = (row) => {
  filterConfigDialog.title = '编辑常用筛选配置'
  filterConfigDialog.visible = true
  Object.assign(filterConfigForm, {
    id: row.id,
    optionCode: row.optionCode,
    optionName: row.optionName,
    metricIds: row.metricIds || [],
    isEnabled: row.isEnabled
  })
}

// 删除常用筛选配置
const handleDeleteFilterConfig = async (row) => {
  try {
    await ElMessageBox.confirm(`确定删除筛选配置 "${row.optionName}" 吗？`, '提示', {
      type: 'warning'
    })

    await deleteCommonFilter(row.id)
    ElMessage.success('删除成功')
    // 删除成功后刷新所有数据
    await refreshAllData()
  } catch {
    // 用户取消删除
  }
}

// 筛选状态变化
const handleFilterStatusChange = async (value,row) => {
  try {
    // 这里应该调用更新接口，但接口文档中没有提供更新接口
    ElMessage.success('状态更新成功')
    await setCommonFilter({
      id: row.id,
      isEnabled: value
    });
    // 刷新数据
    await loadCommonFilterList()
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('更新状态失败')
  }
}

// 监测量选择变化
const handleMetricChange = (metricId) => {
  const selectedMetric = monitoringList.value.find(item => item.monitorId === metricId)
  if (selectedMetric) {
    commonConfigForm.metricCode = selectedMetric.monitorCode
    if (!commonConfigForm.aliasName) {
      commonConfigForm.aliasName = selectedMetric.monitorName
    }
    if (!commonConfigForm.aliasUnit) {
      commonConfigForm.aliasUnit = selectedMetric.monitorUnit
    }
  }
}

// 保存常用监测量配置
const saveCommonConfig = async () => {
  try {
    // 表单验证
    // 这里应该调用保存接口，但接口文档中没有提供保存接口
    ElMessage.success('保存成功')
    commonConfigDialog.visible = false
    // 保存成功后刷新所有数据
    await refreshAllData()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 保存常用筛选配置
const saveFilterConfig = async () => {
  try {
    // 表单验证
    if (filterConfigForm.id) {
      // 编辑操作 - 接口文档中没有提供更新接口
    } else {
      // 新增操作
      await addCommonFilter(filterConfigForm)
    }

    ElMessage.success('保存成功')
    filterConfigDialog.visible = false
    // 保存成功后刷新所有数据
    await refreshAllData()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 重置表单
const resetCommonConfigForm = () => {
  Object.assign(commonConfigForm, {
    id: null,
    metricId: '',
    metricCode: '',
    aliasName: '',
    aliasUnit: '',
    orderNo: 0,
    isCommon: 1,
    enabled: 1,
    remark: ''
  })
}

const resetFilterConfigForm = () => {
  Object.assign(filterConfigForm, {
    id: null,
    optionCode: '',
    optionName: '',
    metricIds: [],
    isEnabled: 1
  })
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.overview-card {
  margin-bottom: 20px;
}

.overview-content {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #409eff;
  font-size: 14px;
  line-height: 1.6;
  color: #606266;
  white-space: pre-wrap;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #ebeef5;
}

.mt-2 {
  margin-top: 20px;
}

.monitoring-list-card,
.common-config-card,
.filter-config-card {
  height: auto;
  min-height: 200px;
  overflow: hidden;
}

.table-container {
  position: relative;
}

/* 表格样式优化 */
:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table .cell) {
  padding: 8px 12px;
}

:deep(.el-card__header) {
  padding: 0;
  border-bottom: none;
}

:deep(.el-card__body) {
  padding: 0;
}

/* 固定表头样式 - 使用Element Plus内置的height属性实现固定表头 */
:deep(.el-table__header-wrapper) {
  position: sticky;
  top: 0;
  z-index: 100;
}

:deep(.el-table__fixed-header-wrapper) {
  position: sticky;
  top: 0;
  z-index: 101;
}

/* 固定列样式 */
:deep(.el-table__fixed) {
  z-index: 102;
}

:deep(.el-table__fixed-right) {
  z-index: 102;
}

/* 滚动条样式优化 */
:deep(.el-table__body-wrapper)::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
}

.dialog-form {
  max-height: 500px;
  overflow-y: auto;
}

.status-tag {
  margin: 0 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .table-container {
    max-height: 300px;
  }
}
</style>